package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Tag(name = "菜品相关接口")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;

    @Autowired
    RedisTemplate redisTemplate;

    @Operation(summary = "新增菜品")
    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品：{}", dishDTO);
        dishService.save(dishDTO);
        //清楚缓存数据
        String key = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(key);
        return Result.success();
    }

    @Operation(summary = "菜品分页查询")
    @GetMapping("/page")
    public Result page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("菜品分页查询：{}", dishPageQueryDTO);
        return dishService.page(dishPageQueryDTO);
    }

    @Operation(summary = "批量删除菜品")
    @DeleteMapping
    public Result delete(@RequestParam("ids") List<Long> ids) {
        log.info("批量删除菜品：{}", ids);
        dishService.delete(ids);
        //批量删除的话粗暴一点直接全部删除缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return Result.success();
    }

    @Operation(summary = "修改菜品起售禁售信息")
    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status, Long id ){
        log.info("修改菜品起售禁售信息：{}", id);
        dishService.startOrStop(status,id);
        //清除缓存
        Result<DishVO> byId = dishService.getById(id);
        String key = "dish_" + byId.getData().getCategoryId();
        redisTemplate.delete(key);
        return Result.success();
    }

    @Operation(summary = "根据菜品id查询菜品")
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id) {
        log.info("根据id查询菜品：{}", id);
        return dishService.getById(id);
    }

    @Operation(summary = "修改菜品")
    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品：{}", dishDTO);
        dishService.update(dishDTO);
        //修改操作比较复杂,可能修改分类id导致一个分类的缓存数据少一个另一个分类的数据多一个,粗暴处理直接全删
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return Result.success();
    }
    @GetMapping("/list")
    @Operation(summary = "根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId){
        List<Dish> list = dishService.list(categoryId);
        return Result.success(list);
    }

}
